package com.kepler.servlet.user;

import com.kepler.pojo.User;
import com.kepler.service.user.UserService;
import com.kepler.service.user.UserServiceImpl;
import com.kepler.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lenovo
 */
public class LoginServlet extends HttpServlet {
    // Servlet：控制层调用业务层代码

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet--start....");

        // 获取用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        // 和数据库中的密码进行对比，调用业务层
        UserService userService = new UserServiceImpl();
        // 这里已经把登录的人查出来了
        User user = userService.login(userCode, userPassword);

        if (user != null && userPassword.equals(user.getUserPassword())){
            // 查有此人验证密码后，可以登录
            // 将用户的信息放到Session中
            req.getSession().setAttribute(Constant.USER_SESSION, user);
            // 跳转到内部主页
            resp.sendRedirect("jsp/frame.jsp");
        } else {
            // 查无此人，无法登录
            // 转发会登录界面，顺带提示错误
            req.setAttribute("error", "用户名或者密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
